package com.sun.showcase.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.sun.showcase.conf.security.UserInfoDetails;
import com.sun.showcase.utils.LoginContext;
import com.sun.showcase.utils.LoginContextHolder;
@Component
public class LoginContextInterceptor extends HandlerInterceptorAdapter {
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//return super.preHandle(request, response, handler);
		try {
			Authentication auth = SecurityContextHolder.getContext().getAuthentication();
			if(auth != null && auth.getPrincipal() != null && auth.getPrincipal() instanceof UserInfoDetails){
				//已登路，将当期登录者信息保存到线程上下文中
				LoginContext loginContext = buildLoginContext((UserInfoDetails)auth.getPrincipal());
				LoginContextHolder.put(loginContext);
			}
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
		LoginContextHolder.clear();//本次访问结束，清除信息。
	}

	private LoginContext buildLoginContext(UserInfoDetails userInfo){
		
		LoginContext loginContext = createLoginContext();
		loginContext.setUserId(userInfo.getId());
		loginContext.setUserName(userInfo.getName());
		loginContext.setUserNickName(userInfo.getNickName());

		return loginContext;
	}
	protected LoginContext createLoginContext(){
		return new LoginContext();
	}
}
